package org.crackjack.services;

import java.util.List;

import org.crackjack.dao.AppointmentDao;
import org.crackjack.model.Appointment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/appointment", headers = "Accept=application/json")
public class AppointmentController extends GenericController {

    @Autowired
    private AppointmentDao appointmentDao;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<List<Appointment>> getAppointments() {
        List<Appointment> appointments = appointmentDao.getList();
        for (Appointment a : appointments) {
            a.getAppointmentOwner().setAppointments(null);
            a.getCategory().setAppointments(null);
        }

        return getResponseInJsonType(appointments);

    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Appointment> getAppointment(@PathVariable("id") long id) {
        return getResponseInJsonType(appointmentDao.get(id));

    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public void deleteAppointment(@RequestBody Appointment appointment) {
        appointmentDao.delete(appointment);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public void deleteAppointment(@PathVariable("id") long id) {
        appointmentDao.delete(id);
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public void updateAppointment(@RequestBody Appointment appointment) {
        appointmentDao.update(appointment);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public void saveAppointment(@RequestBody Appointment appointment) {
        appointmentDao.create(appointment);
    }

}
